package com.web.kdl.service.device;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.web.kdl.daoV2.device.DeviceMapper;
import com.web.kdl.entity.device.DeviceInfo;
import com.web.kdl.pojo.form.DeviceForm;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DeviceServiceImpl implements DeviceService{
    private final DeviceMapper deviceMapper;

    @Override
    public List<DeviceInfo> query(String deviceName) {
        //mybatisPlus 模糊查询
        LambdaQueryWrapper<DeviceInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (deviceName != null){
            queryWrapper.like(DeviceInfo::getDeviceName,deviceName);
        }
        return deviceMapper.selectList(queryWrapper);
    }

    @Override
    public List<DeviceInfo> queryUnion(DeviceForm deviceForm) {
        LambdaQueryWrapper<DeviceInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (deviceForm.getDeviceName() != null && !deviceForm.getDeviceName().isEmpty()){
            queryWrapper.like(DeviceInfo::getDeviceName,deviceForm.getDeviceName());
        }
        if (deviceForm.getAddress() != null){
            int add = getAdd(deviceForm);
            queryWrapper.like(DeviceInfo::getAddress,add);
        }
        return deviceMapper.selectList(queryWrapper);
    }

    private static int getAdd(DeviceForm deviceForm) {
        int add = 0;
        if (deviceForm.getAddress()<40200){
            add = deviceForm.getAddress();
        } else if (deviceForm.getAddress()< 40400) {
            add = deviceForm.getAddress()-200;
        } else if (deviceForm.getAddress()<40600) {
            add = deviceForm.getAddress()-400;
        }else if (deviceForm.getAddress()< 40800){
            add = deviceForm.getAddress()-600;
        }else{
            add = deviceForm.getAddress();
        }
        return add;
    }

    @Override
    public List<String> getAllDevice() {
        LambdaQueryWrapper<DeviceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(DeviceInfo::getDeviceName);
        List<DeviceInfo> deviceInfos = deviceMapper.selectList(queryWrapper);
        return deviceInfos.stream()
                .map(DeviceInfo::getDeviceName)
                .collect(Collectors.toList());
    }

}
